package com.itcam.reflect_.msb03;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * Author:Cammy.Wu
 * Date:2024-05-22
 * Description:
 */
/**
 *
 */
public class Test03 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 获取字节码信息
        Class cls = Student.class;

        // 获取方法
        // getMethods:获取运行时类的方法还有所有父类中的方法（被public修饰的）
        Method[] methods = cls.getMethods();
        for (Method method : methods) {
            System.out.println("method = " + method);
        }

        System.out.println("-------------------------------------------------");

        // getDeclareMethods:获取运行时类中的所有方法
        Method[] declaredMethods = cls.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println("declaredMethod = " + declaredMethod);
        }

        System.out.println("-------------------------------------------------");

        // 获取指定的方法
        Method methods1 = cls.getMethod("showInfo");
        System.out.println(methods1);
        Method methods2 = cls.getMethod("showInfo", int.class, int.class);
        System.out.println(methods2);
        Method work = cls.getDeclaredMethod("work");
        System.out.println(work);

        System.out.println("-------------------------------------------------");

        // 获取方法的具体结构
        /**
         * @注解
         * 修饰符 返回值类型 方法名（参数列表） throws xxx()
         *
         */

        // 名字
        System.out.println(work.getName());

        // 修饰符
//        int modifiers = work.getModifiers();
        System.out.println(Modifier.toString(work.getModifiers()));

        //返回值
        System.out.println(work.getReturnType());

        // 参数列表
        Class[] parameterTypes = work.getParameterTypes();
        for (Class parameterType : parameterTypes) {
            System.out.println("parameterType = " + parameterType);
        }

        // 获取注解
        Method myMethod = cls.getMethod("myMethod");
        Annotation[] annotations = myMethod.getAnnotations(); // SOURCE的注解获取不到
        for (Annotation annotation : annotations) {
            System.out.println("annotation = " + annotation);
        }

        // 获取异常
        Class[] exceptionTypes = myMethod.getExceptionTypes();
        for (Class exceptionType : exceptionTypes) {
            System.out.println("exceptionType = " + exceptionType);
        }

        // 调用方法
        Object o = cls.getDeclaredConstructor().newInstance();
        myMethod.invoke(o);
        System.out.println(methods2.invoke(o, 3, 4));
    }
}
